﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;

namespace TileSetConverter
{
    class Palette
    {
        Color[] palette = new Color[256];

        public Color[] ColorPalette
        {
            get { return palette; }
            set { palette = value; }
        }

        public Palette(string paletteFilename)
        {
            FileStream fs = new FileStream(paletteFilename, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            for (int i = 0; i < 256; i++)
            {
                palette[i] = this.ReadColor(br);
            }
            br.Close();
            fs.Close();
        }
        private Color ReadColor(BinaryReader br)
        {
            byte source;
            float converted;
            source = br.ReadByte();
            converted = (255.0f / 63.0f) * source;
            byte r = Convert.ToByte(converted);

            source = br.ReadByte();
            converted = (255.0f / 63.0f) * source;
            byte g = Convert.ToByte(converted);

            source = br.ReadByte();
            converted = (255.0f / 63.0f) * source;
            byte b = Convert.ToByte(converted);

            return Color.FromArgb(r, g, b);
        }
        internal  Color GetNearestColor(Color testColor)
        {
            int index = 0;
            double currentDistance = 195075;
            Color paletteColor;
            for (int i = 0; i < 256; i++)
            {
                paletteColor = palette[i];
                int redDistance = paletteColor.R - testColor.R;
                int greenDistance = paletteColor.G - testColor.G;
                int blueDistance = paletteColor.B - testColor.B;

                int distance = (redDistance * redDistance) +
                                    (greenDistance * greenDistance) +
                                    (blueDistance * blueDistance);

                if (distance < currentDistance)
                {
                    index = i;
                    currentDistance = distance;
                }
            }
            return palette[index];
        }
    }
}
